package org.sky.framework.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.sky.framework.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.mvc.Controller;

import com.google.gson.Gson;

/**
 * 请求controller切面
 * 
 * @author gaofu
 *
 */
@Aspect
public class RequestAspect {
	protected static final Logger logger = LoggerFactory.getLogger(RequestAspect.class);
	public static final String CONTROLLER_POINTCUT = "@annotation(org.springframework.web.bind.annotation.RequestMapping)"
			+ "||@annotation(org.springframework.web.bind.annotation.GetMapping)"
			+ "||@annotation(org.springframework.web.bind.annotation.PostMapping)"
			+ "||@annotation(org.springframework.web.bind.annotation.PutMapping)"
			+ "||@annotation(org.springframework.web.bind.annotation.PatchMapping)"
			+ "||@annotation(org.springframework.web.bind.annotation.DeleteMapping)";

	protected Gson gson = Utils.getGsonBuilder().serializeNulls().create();

	@Around(CONTROLLER_POINTCUT)
	public Object controllerAround(ProceedingJoinPoint pjp) {
		Object result = null;
		try {
			// 校验
			Class<?> targetClass = AopUtil.pointClass(pjp);
			Method targetMethod = AopUtil.pointMethod(pjp);
			boolean isController = AopUtil.isController(targetClass.getAnnotations());
			if (isController || Controller.class.isAssignableFrom(targetClass)) {
				requestVerify(targetClass, targetMethod);
			}
			// 执行目标方法
			result = pjp.proceed();
		} catch (Throwable t) {
			logger.error("", t);
		}
		return result;
	}

	/**
	 * 请求controller校验
	 * 
	 * @param targetClass  controller类
	 * @param targetMethod controller方法
	 * @throws Exception
	 */
	protected void requestVerify(Class<?> targetClass, Method targetMethod) throws Exception {
	}

}
